import 'package:flutter/material.dart';
import '../models/song.dart';
import '../widgets/song_list_widget.dart';
import '../services/favorites_service.dart';
import '../services/custom_playlist_service.dart';
import 'package:file_selector/file_selector.dart' as fs;
import 'dart:io' show Platform;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

class FavoritesScreen extends StatefulWidget {
  const FavoritesScreen({super.key});

  @override
  State<FavoritesScreen> createState() => _FavoritesScreenState();
}

class _FavoritesScreenState extends State<FavoritesScreen> {
  List<Song> _favorites = [];
  List<Song> _customPlaylist = [];
  bool _isLoadingFavorites = true;
  bool _isLoadingCustom = true;

  @override
  void initState() {
    super.initState();
    _loadFavorites();
    _loadCustomPlaylist();
    
    // 监听收藏状态变化
    FavoritesService.addListener(_onFavoritesChanged);
    CustomPlaylistService.addListener(_onCustomChanged);
  }

  @override
  void dispose() {
    FavoritesService.removeListener(_onFavoritesChanged);
    CustomPlaylistService.removeListener(_onCustomChanged);
    super.dispose();
  }

  void _onFavoritesChanged() {
    // 当收藏状态改变时，重新加载收藏列表
    _loadFavorites();
  }

  void _onCustomChanged() {
    _loadCustomPlaylist();
  }

  Future<void> _loadFavorites() async {
    try {
      final favorites = await FavoritesService.getFavorites();
      if (mounted) {
        setState(() {
          _favorites = favorites;
          _isLoadingFavorites = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingFavorites = false;
        });
      }
    }
  }

  Future<void> _loadCustomPlaylist() async {
    try {
      final playlist = await CustomPlaylistService.getPlaylist();
      if (mounted) {
        setState(() {
          _customPlaylist = playlist;
          _isLoadingCustom = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingCustom = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '收藏夹',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: Theme.of(context).colorScheme.surface,
        foregroundColor: Theme.of(context).colorScheme.onSurface,
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 12),
            // 我喜欢分区
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Icon(Icons.favorite, color: Theme.of(context).colorScheme.primary),
                  const SizedBox(width: 8),
                  Text(
                    '我喜欢',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
                  ),
                  const Spacer(),
                  Text('共 ${_favorites.length} 首', style: Theme.of(context).textTheme.bodyMedium),
                  const SizedBox(width: 8),
                  _buildActionChip('导出', Icons.download, _exportFavorites),
                  const SizedBox(width: 8),
                  _buildActionChip('导入', Icons.upload, _importFavorites),
                ],
              ),
            ),
            const SizedBox(height: 12),
            if (_isLoadingFavorites)
              const Center(child: Padding(padding: EdgeInsets.all(20), child: CircularProgressIndicator()))
            else if (_favorites.isEmpty)
              _buildEmptyState()
            else
              SizedBox(
                height: 320,
                child: SongListWidget(
                  songs: _favorites,
                  onSongTap: (song, index) {},
                  onDeleteTap: (song, index) => _showDeleteConfirmDialog(song),
                ),
              ),

            const SizedBox(height: 20),

            // 自定义歌单分区
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Icon(Icons.queue_music, color: Theme.of(context).colorScheme.primary),
                  const SizedBox(width: 8),
                  Text(
                    '自定义歌单',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
                  ),
                  const Spacer(),
                  Text('共 ${_customPlaylist.length} 首', style: Theme.of(context).textTheme.bodyMedium),
                  const SizedBox(width: 8),
                  _buildActionChip('导出', Icons.download, _exportCustom),
                  const SizedBox(width: 8),
                  _buildActionChip('导入', Icons.upload, _importCustom),
                ],
              ),
            ),
            const SizedBox(height: 12),
            if (_isLoadingCustom)
              const Center(child: Padding(padding: EdgeInsets.all(20), child: CircularProgressIndicator()))
            else if (_customPlaylist.isEmpty)
              _buildEmptyCustomState()
            else
              SizedBox(
                height: 320,
                child: SongListWidget(
                  songs: _customPlaylist,
                  onSongTap: (song, index) {},
                ),
              ),
            const SizedBox(height: 12),
          ],
        ),
      ),
    );
  }

  void _showDeleteConfirmDialog(Song song) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: Text('确定要从收藏夹中删除 "${song.name}" 吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _deleteFavorite(song);
              },
              child: const Text('删除'),
            ),
          ],
        );
      },
    );
  }

  void _deleteFavorite(Song song) async {
    try {
      await FavoritesService.removeFromFavorites(song);
      _loadFavorites(); // 重新加载收藏夹
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('已从收藏夹中删除 "${song.name}"'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Theme.of(context).colorScheme.error,
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }

  // ===== 导入/导出相关 =====
  Widget _buildActionChip(String label, IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.blue.withOpacity(0.08),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.blue.withOpacity(0.3)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 16, color: Colors.blue[600]),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(fontSize: 12, color: Colors.blue[600], fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _exportFavorites() async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/favorites_export.json';
        final path = await FavoritesService.exportFavoritesToFile(tempPath);
        if (path == null) throw Exception('生成导出文件失败');
        await Share.shareXFiles([XFile(path!)], text: '分享“我喜欢”歌单文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出并打开系统分享面板')),
          );
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: 'favorites_export.json',
        );
        if (location == null) return;
        final path = await FavoritesService.exportFavoritesToFile(location.path);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(path != null ? '已导出到: $path' : '导出失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _importFavorites() async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await FavoritesService.importFavoritesFromFile(file.path);
      await _loadFavorites();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从 ${file.path} 导入 $count 首到“我喜欢”')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  Future<void> _exportCustom() async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/ly_music_custom_playlist.json';
        final path = await CustomPlaylistService.exportToFile(filePath: tempPath);
        if (path == null) throw Exception('生成导出文件失败');
        await Share.shareXFiles([XFile(path!)], text: '分享“自定义歌单”文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出并打开系统分享面板')),
          );
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: 'ly_music_custom_playlist.json',
        );
        if (location == null) return;
        final path = await CustomPlaylistService.exportToFile(filePath: location.path);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(path != null ? '已导出到: $path' : '导出失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _importCustom() async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await CustomPlaylistService.importFromFile(filePath: file.path);
      await _loadCustomPlaylist();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从 ${file.path} 导入 $count 首到“自定义歌单”')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(60),
            ),
            child: Icon(
              Icons.favorite_border,
              size: 60,
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
          const SizedBox(height: 24),
          Text(
            '还没有收藏的歌曲',
            style: Theme.of(context).textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w600,
              color: Theme.of(context).colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '去搜索并收藏你喜欢的音乐吧',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 32),
          ElevatedButton.icon(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: const Icon(Icons.search),
            label: const Text('去搜索音乐'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.primary,
              foregroundColor: Theme.of(context).colorScheme.onPrimary,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyCustomState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(60),
            ),
            child: Icon(
              Icons.queue_music,
              size: 60,
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
          const SizedBox(height: 24),
          Text(
            '还没有自定义歌单',
            style: Theme.of(context).textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w600,
              color: Theme.of(context).colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '你可以从搜索结果添加歌曲',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ),
    );
  }
}